const utils = require('root/utils')
const { extname } = require('path')
const path = require('path')
const nuid = require('nuid')

const fileService = {
  // 列表
  upload(req, res) {
    // 读取上传文件的内容
    const file = req.files.file
    const time = utils.getDayjs()
    const time2 = utils.getDayjs('HHmmss')
    const mimeType = file.mimetype.split('/')[1]
    const media = utils.isImage(mimeType) ? 'image' : 'other'
    // 处理上传文件

    const publicPath = `/public/uploads/${media}/${time}/${Math.round(Math.random() * 1e9)}_${nuid.next()}_${time2}${extname(file.name)}`
    const filePath = path.join(__dirname, '../../', publicPath)

    file.mv(filePath, function(err) {
      if (err) {
        return res.cc('上传失败！', err)
      }
    })

    return res.cc('success', 0, { data: publicPath })
  },
  // 详情
}

module.exports = fileService
